const express = require("express");
const router = express.Router();
const secretKey = "3uX#7%r&2@!P5cK8";
const expressJWT = require("express-jwt");
const jwt = require("jsonwebtoken");
const User = require("../models/User");
const crypto = require('crypto');
// 登录接口
router.post('/login', async (req, res) => {
    try {
        const { phoneNumber, password } = req.body;
        const user = await User.findOne({ phoneNumber });
        if (user && user.password === password) {
            const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: "1h" })
            res.status(200).json({
                statusCode: 200,
                status: 'success',
                message: '登录成功',
                token: token,
                userData: {
                    id: user.id,
                    uid: user.uid,
                    username: user.username,
                    personSignature: user.personSignature,
                }
            });
        } else {
            res.status(401).json({ statusCode: 401, status: 'error', message: '电话号或密码输入不正确' });
        }
        console.log(phoneNumber, password);
    } catch (error) {
        console.error(error);
        res.status(500).json({ statusCode: 500, status: 'error', message: '服务器错误' });
    }
})
router.post('/email', async (req, res) => {
    try {
        const { email, password } = req.body;
        const user = await User.findOne({ email });
        if (!user) {
            return res.status(401).json({ error: '用户不存在' });
        }
        const storedPassword = user.password; // 存储的哈希密码和盐值
        const [hash, salt] = storedPassword.split('.');
        const passwordHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha256').toString('hex');
        if (hash === passwordHash) {
            // 登录成功
            const token = jwt.sign({ userId: user.id }, secretKey, { expiresIn: "1h" })
            res.status(200).json({
                statusCode: 200,
                status: 'success',
                message: '登录成功',
                token: token,
                userData: {
                    id: user.id,
                    uid: user.uid,
                    username: user.username,
                    personSignature: user.personSignature,
                }
            });
            // return res.status(200).json({ message: '登录成功' });
        } else {
            // 密码不匹配
            return res.status(401).json({ error: '密码不正确' });
        }
        console.log(email, password);
    } catch (error) {
        console.error(error);
        res.status(500).json({ statusCode: 500, status: 'error', message: '服务器错误' });
    }
})

module.exports = router;